<template>
  <div>
    <b-container fluid>
      <b-row class="mb-5">
        <b-input-group class="mt-3" prepend="标题">
          <template #append>
          </template>
          <b-form-input v-model="noteTitle" placeholder="Enter your title"></b-form-input>
          <div hidden>{{ noteTitle }}</div>
        </b-input-group>
      </b-row>

      <b-row class="mb-5">
        <b-form-textarea
            id="textarea-lazy"
            v-model="noteContent"
            placeholder="Enter your text"
            rows="10"
        ></b-form-textarea>
        <div hidden>{{ noteContent }}</div>
      </b-row>
      
      <b-button-group>
        <b-button variant="success" @click="saveNote">保存</b-button>
        <b-button variant="warning" @click="saveAndExit">保存并退出</b-button>
        <b-button @click="recover">恢复</b-button>
        <b-button variant="danger" @click="exitWithoutSave">不保存退出</b-button>
      </b-button-group>
    </b-container>
  </div>
</template>

<script>
import { modifyNote, createNote } from '../api/requests';

export default {
  name: 'Editing',
  data() {
    return {
      notes: [],
      noteTitle: '',
      noteContent: '',
      note: {}
    }
  },
  created() {
    this.fillTheForm(this.$route.params.id);
  },
  methods: {
    getNotes() {
      var noteStr = localStorage.getItem("notebooklist");
      if (noteStr) {
        this.notes = JSON.parse(noteStr);
      }
    },
    fillTheForm(noteId) {
      if (noteId === -1) {
        this.note = null;
      }else {
        this.getNotes();
        this.notes.forEach(n => {
          if (n.noteId === noteId) {
            this.note = n;
          }
        });
        this.noteTitle = this.note.title;
        this.noteContent = this.note.content;
      }
    },
    async saveNote() {
      if (this.noteTitle.trim().length === 0) {
        this.$bvModal.msgBoxOk('标题为空无法保存');
        return false;
      }
      var res;
      if (this.note === null) {
        if (this.noteTitle !== null && this.noteTitle.trim().length > 0) {
          this.note = JSON.parse("{\"title\": \"" + this.noteTitle + "\",\"content\":\"" + this.noteContent + "\"}");
          res = await createNote(this.note);
          if (res) {
            this.getNotes();
            this.notes.push(res);
          }
        }
      }else if (this.note.title !== this.noteTitle.trim() || this.note.content !== this.noteContent.trim()) {
        this.note.title = this.noteTitle;
        this.note.content = this.noteContent;
        this.note.modifyTime = this.formateDateToStr(new Date());
        //后端数据修改成功后才修改localstorage数据
        res = await modifyNote(this.note);
        if (res) {
          for (var i=0; i < this.notes.length; i++) {
            if (this.notes[i].noteId === res.noteId) {
              this.notes[i].title = this.noteTitle;
              this.notes[i].content = this.noteContent;
              localStorage.setItem("notebooklist",JSON.stringify(this.notes));
            }
          }
        }
      }
      return true;
    },
    async saveAndExit() {
      const isSaved = await this.saveNote();
      if (isSaved) {
        this.$router.push('/notebook');
      }
    },
    recover() {
      this.fillTheForm(this.$route.params.id);
    },
    exitWithoutSave() {
      this.$bvModal.msgBoxConfirm('是否不保存退出此备忘录？', {
          title: '请确认',
          size: 'sm',
          buttonSize: 'sm',
          okVariant: 'danger',
          okTitle: '是',
          cancelTitle: '否',
          footerClass: 'p-2',
          hideHeaderClose: false,
          centered: true
      }).then(value => {
          if (value) {
            this.$router.push('/notebook');
          }
      });
    },
    formateDateToStr(date) {
      return date.getFullYear() + '-'
          + this.appendZero(date.getMonth()+1) + '-'
          + this.appendZero(date.getDate()) + ' '
          + this.appendZero(date.getHours()) + ':'
          + this.appendZero(date.getMinutes()) + ':'
          + this.appendZero(date.getSeconds());
    },
    appendZero(date) {
      if (date < 10) return "0" + "" + date;
      return date;
    }
  }
}
</script>

<style scoped>
</style>